﻿using AspectCore.DynamicProxy;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore;
namespace Zy.Shared.Repository.UnitOfWorks
{
    /// <summary>
    /// UnitOfWork
    /// </summary>
    /// <param name="isCapTranslation">是否同步开启CAP事务</param>
    public class UnitOfWorkAttribute(bool isCapTranslation=false) : AbstractInterceptorAttribute
    {
        public bool IsCapTranslation { get; set; } = false;
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var unitOfWork = (IUnitOfWork)context.ServiceProvider.GetService(typeof(IUnitOfWork));
            if (unitOfWork is null)
                throw new ArgumentNullException(nameof(unitOfWork));
            //await unitOfWork.Strategy.ExecuteAsync(async () =>//Mysql驱动不支持这种形式，不要再尝试了
           // {
                try
                {
                    unitOfWork.BeginTransaction(distributed: false);//开启事务前关闭重试
                    await next(context);
                    await unitOfWork.CommitAsync();
                }
                catch (Exception)
                {
                     await unitOfWork.RollbackAsync();
                    throw;
                }
            //});
        }
    }
}
